<?php

class Response {

    private $request;

    // hooks
    const BEFORE_PROCESS_HOOK = 'before_process_hook';
    const AFTER_PROCESS_HOOK = 'after_process_hook';
    const BEFORE_SEND_HOOK = 'before_send_hook';
    const AFTER_SEND_HOOK = 'after_send_hook';

    private static $hooks = array();

    public function __construct($request) {
        $this->request = $request;
    }

    public function process() {
        $controller = $this->request->controller;
        $action = $this->request->action;
        $params = $this->request->params;

        $this->invoke_hooks(self::BEFORE_PROCESS_HOOK);
        if ($controller !== null) {
            $controller->process($action, $params);
        }
        $this->invoke_hooks(self::AFTER_PROCESS_HOOK);
    }

    public function send() {
        $controller = $this->request->controller;
        $action = $this->request->action;

        $this->invoke_hooks(self::BEFORE_SEND_HOOK);
        if ($controller !== null) {
            $controller->render($action);
        } else {
            Mini::oops(500);
        }
        $this->invoke_hooks(self::AFTER_SEND_HOOK);
    }

    public static function hook($hook, $function) {
        self::$hooks[$hook][] = $function;
    }

    private function invoke_hooks($hook) {
        if (!isset(self::$hooks[$hook])) {
            return;
        }

        $hooks = self::$hooks[$hook];
        foreach ($hooks as $h) {
            call_user_func($h);
        }
    }
}